#region File Description
//-----------------------------------------------------------------------------
// MainForm.cs
//
// Microsoft XNA Community Game Platform
// Copyright (C) Microsoft Corporation. All rights reserved.
//-----------------------------------------------------------------------------
#endregion

#region Using Statements
using System.Windows.Forms;
using AimGameLibrary;
#endregion

#region Aim_Engine Using

using System;
using System.IO;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
using System.Reflection;


using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Content;

using ContentLoading; 

using AimGameEngine.Compornet;
using AimGameEngine.Menu;
using AimGameEngine.NodeEditorObject;
using AimGameEngine.NodeTemples;

using AimGameEngine.EditorObject;

#endregion

namespace AimGameEngine
{
    // System.Drawing and the XNA Framework both define Color types.
    // To avoid conflicts, we define shortcut names for them both.
    using GdiColor = System.Drawing.Color;
    using XnaColor = Microsoft.Xna.Framework.Color;

    /// <summary>
    /// Custom form provides the main user interface for the program.
    /// In this sample we used the designer to add a splitter pane to the form,
    /// which contains a SpriteFontControl and a SpinningTriangleControl.
    /// </summary>
    public partial class MainForm : Form
    {
        NodeList MyNodeList;
        NodeTempleList MyNodeTempleList;

        public const String BuildPath = "Content";

        const String SaveLoad_PartPosition = "PartListPosition";
        const String SaveLoad_PartGroup = "PartGroup";
        ControlContentBuilder controlcontentbuilder;
        public Script create;
        //bool testXML = false;
        public MainForm()
        {
            InitializeComponent();
            create = new Script();

            SettingEditorData Data = new SettingEditorData();
            XMLData<SettingEditorData> load = new XMLData<SettingEditorData>();

            if (File.Exists(Script.SettingFile))
                Data = load.Load(Script.SettingFile);
            else
            {
                string assemblyLocation = Assembly.GetExecutingAssembly().Location;
                string relativePath = Path.Combine(assemblyLocation, "..");
                string contentPath = Path.GetFullPath(relativePath);

                string releasemode = Path.Combine(contentPath, "Game");
                Data.SettingDefualt(releasemode);
                load.Save(Data, Path.Combine(contentPath,Script.SettingFile));
            }

            controlcontentbuilder = new ControlContentBuilder(spritePreviewControl1.Services, false,BuildPath, Data.BuildOutput);
            
        }

        private void MainForm_Load(object sender, System.EventArgs e)
        {
            MyNodeList = new NodeList();
            MyNodeTempleList = new NodeTempleList();
            SettingNodeList();

            spriteNodeControl1.AllowDrop = true;
            spriteNodeControl1.backupaction.SetupButton(this.UndoButton, this.RedoButton);
            spriteNodeControl1.CreateNewProject(MyNodeList);
        }

        #region Event Menubar

        private void File_Exit_Click(object sender, System.EventArgs e)
        {
            this.Close();
        }

        private void optionToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Option option = new Option();
            option.ShowDialog();
        }

        private void aboutToolStripMenuItem_Click(object sender, EventArgs e)
        {
            About about = new About();
            about.ShowDialog();
        }

        #endregion

        #region Event Shoutcut

        private void saveToolStripMenuItem1_Click(object sender, EventArgs e)
        { 
            SaveFileDialog savefile = new SaveFileDialog();
            // Default to the directory which contains our content files.
            string assemblyLocation = Assembly.GetExecutingAssembly().Location;
            string relativePath = Path.Combine(assemblyLocation, "../../../../Content");
            string contentPath = Path.GetFullPath(relativePath);

            savefile.InitialDirectory = contentPath;

            savefile.Title = "Save an Aim Game Engine Project File";

            savefile.Filter = "Aim Game Engine Project (*.aegp)|*.aegp";

            if (savefile.ShowDialog() == DialogResult.OK)
            {
                if (savefile.FileName != "")
                {
                    SaveDataProject(spriteNodeControl1.MainDictionaryType.GetMaindictionarY[DictionaryType.MainObejct], savefile.FileName);
                }
                //this.EXEpath.Text = file.FileName;
            }
            
        }

        private void saveAsToolStripMenuItem_Click(object sender, EventArgs e)
        {

        }

        private void OpenButton_Click(object sender, EventArgs e)
        {
            OpenFileDialog file = new OpenFileDialog();
            // Default to the directory which contains our content files.
            string assemblyLocation = Assembly.GetExecutingAssembly().Location;
            string relativePath = Path.Combine(assemblyLocation, "../../../../Content");
            string contentPath = Path.GetFullPath(relativePath);

            file.InitialDirectory = contentPath;

            file.Title = "Open an Aim Game Engine Project File";

            file.Filter = "Aim Game Engine Project (*.aegp)|*.aegp";

            if (file.ShowDialog() == DialogResult.OK)
            {
                if (file.FileName != "")
                {
                    XMLData<Identification> loaddata = new XMLData<Identification>();
                    Identification identificationScreen = new Identification();
                    identificationScreen = loaddata.Load(file.FileName);
                    LoadDataProject(identificationScreen);
                }
            }
        }

        private void newButton_Click(object sender, EventArgs e)
        {
            spriteNodeControl1.backupaction.ClearAll();
            spriteNodeControl1.ClearALL();
            spriteNodeControl1.CreateNewProject(MyNodeList);
        }

        private void EditButton_Click(object sender, EventArgs e)
        {

        }

        private void PlayGameButton_Click(object sender, EventArgs e)
        {
            XMLData<SettingEditorData> Load = new XMLData<SettingEditorData>();
            SettingEditorData temp = Load.Load(Script.SettingFile);
            Process p = Process.Start(temp.EXEpath);
        }

        private void BuildButton_Click(object sender, EventArgs e)
        {
            Cursor = Cursors.WaitCursor;

            float count = 1;
            String TempName = "";
            string path = controlcontentbuilder.contentManager.RootDirectory;

            #region Video Build

            String Videospath = System.IO.Path.Combine(path, Script.SubVideo);

            if (!System.IO.Directory.Exists(Videospath))
                System.IO.Directory.CreateDirectory(Videospath);

            foreach (String Key in spriteNodeControl1.MainDictionaryType.GetMaindictionarY[NodeTypeValue.VideoPlayer.ToString()].Keys)
            {
                NodeVideoPlayer video = (NodeVideoPlayer)spriteNodeControl1.MainDictionaryType.GetMaindictionarY[NodeTypeValue.VideoPlayer.ToString()][Key];
                if (video.MyData.Data != null)
                {
                    controlcontentbuilder.SettingProprety(new ContentProperties(video.MyData.Data, Path.GetFileNameWithoutExtension(video.GetFilE), null, ProcessorContent.VideoProcessor));

                    if (controlcontentbuilder.ContentBuilding() != null)
                        MessageBox.Show(controlcontentbuilder.ContentBuilding());

                    #region Copy and Delete File
                    File.Copy(Path.Combine(path, Path.GetFileNameWithoutExtension(video.GetFilE) + ".xnb")
                        , Path.Combine(Path.Combine(path, Script.SubVideo), Path.GetFileNameWithoutExtension(video.GetFilE) + ".xnb"), true);

                    File.Copy(Path.Combine(path, video.GetFilE)
                       , Path.Combine(Path.Combine(path, Script.SubVideo), video.GetFilE), true);


                    File.Delete(Path.Combine(path, Path.GetFileNameWithoutExtension(video.GetFilE) + ".xnb"));
                    File.Delete(Path.Combine(path, video.GetFilE));
                    #endregion

                }
                else
                {
                    MessageBox.Show("Not Setting Path : " + video.MyData.MyName);
                }
            }

            #endregion

            #region Texture Build
            foreach (String Key in spriteNodeControl1.MainDictionaryType.GetMaindictionarY[NodeTypeValue.Texture2D.ToString()].Keys)
            {
                NodeObject node = spriteNodeControl1.MainDictionaryType.GetMaindictionarY[NodeTypeValue.Texture2D.ToString()][Key];
                if (node.MyData.Data != null && File.Exists(node.MyData.Data))
                {
                    node.MyData.Data = Path.GetFullPath(node.MyData.Data);
                    if (count > 1)
                        File.Copy(Path.Combine(path, TempName + ".xnb"), Path.Combine(path, TempName + "1.xnb"));
                    
                    controlcontentbuilder.SettingProprety(new ContentProperties(node.MyData.Data, node.MyData.MyName, null, ProcessorContent.TextureProcessor));

                    if (controlcontentbuilder.ContentBuilding() != null)
                        MessageBox.Show(controlcontentbuilder.ContentBuilding());

                    if (count > 1)
                    {
                        File.Copy(Path.Combine(path, TempName + "1.xnb"), Path.Combine(path, TempName + ".xnb"));
                        File.Delete(Path.Combine(path, TempName + "1.xnb"));
                    }

                    this.ProgressBar1.Value = (int)((count / (float)spriteNodeControl1.MainDictionaryType.GetMaindictionarY[NodeTypeValue.Texture2D.ToString()].Count) * 100);

                    count++;
                    TempName = node.MyData.MyName;
                }
                else
                {
                    MessageBox.Show("Not Setting Path : " + node.MyData.MyName);
                }
            }
            #endregion

            MessageBox.Show("Complete");
            this.ProgressBar1.Value = 0;
            
            Cursor = Cursors.Arrow;
        }

        private void CleanResouceButton_Click(object sender, EventArgs e)
        {
            Cursor = Cursors.WaitCursor;

            if (spriteNodeControl1.MainDictionaryType.GetMaindictionarY[NodeTypeValue.Texture2D.ToString()].Count > 0)
            {
                String path = controlcontentbuilder.contentManager.RootDirectory + "\\";
                foreach (String Key in spriteNodeControl1.MainDictionaryType.GetMaindictionarY[NodeTypeValue.Texture2D.ToString()].Keys)
                {
                    NodeObject node = spriteNodeControl1.MainDictionaryType.GetMaindictionarY[NodeTypeValue.Texture2D.ToString()][Key];
                    if (node.MyData.Data != null)
                    {
                        if (File.Exists(path + node.MyData.MyName + ".xnb"))
                            File.Delete(path + node.MyData.MyName + ".xnb");
                    }
                }
                MessageBox.Show("Clean Complete");
            }
            else
            {
                MessageBox.Show("Not Resouce to Clean");
            }

            Cursor = Cursors.Arrow;
        }

        private void RefreshButton_Click(object sender, EventArgs e)
        {
            Cursor = Cursors.WaitCursor;

            /// New Load Data by XML
            spritePreviewControl1.Refresh(controlcontentbuilder.contentManager,create);
            Cursor = Cursors.Arrow;
        }

        private void UndoButton_ButtonClick(object sender, EventArgs e)
        {
            spriteNodeControl1.Undo();
        }

        private void RedoButton_ButtonClick(object sender, EventArgs e)
        {
            spriteNodeControl1.Redo();
        }

        private void startHereToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (this.spriteNodeControl1.NodeselecT.GetType() == typeof(NodeScreen))
            {
                NodeScreen screen = (NodeScreen)spriteNodeControl1.NodeselecT;
                screen.Restete();
                screen.StartherE = true;
            }

        }

        private void groupToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (this.spriteNodeControl1.rectangleselect.NodeSelect.Count > 0)
                spriteNodeControl1.CreateGroup();
        }
        private void renameStripMenuItem1_Click(object sender, EventArgs e)
        {
            if (spriteNodeControl1.NodeselecT != null)
                spriteNodeControl1.NodeselecT.Rename();
        }
        private void deleteStripMenuItem1_Click(object sender, EventArgs e)
        {
            if (spriteNodeControl1.NodeselecT != null)
                spriteNodeControl1.DeleteNode();
        }

        #endregion

        #region Setting Node List
        public void SettingNodeList()
        {
            #region Add Node to TreeView
            treeAdvanceNode.ImageList = MyNodeList.imagelist;

            TreeNodeEditor TempNameRoot = new TreeNodeEditor();
            foreach (String Key in MyNodeList.ListNode.Keys)
            {
                NodeData nodedata = MyNodeList.ListNode[Key];

                TreeNodeEditor treenodeeditor = new TreeNodeEditor();
                treenodeeditor.Name = nodedata.MyName;
                treenodeeditor.Text = nodedata.MyName;
                
                treenodeeditor.MyDatA = nodedata;
                treenodeeditor.ToolTipText = nodedata.MyName;
                //treenodeeditor.

                
                //M/yTreeNodeList.Add(temp.MyName, tempTreeNode);
                // 0 = Root
                if (nodedata.MyLevel == 0)
                {
                    this.treeAdvanceNode.Nodes.Add(treenodeeditor);
                    TempNameRoot = treenodeeditor;
                    treenodeeditor.ImageIndex = 0;
                }
                else
                {
                    TempNameRoot.Nodes.Add(treenodeeditor);
                    treenodeeditor.ImageIndex = nodedata.IndexImage;
                }
            }
            #endregion

            #region Add Temple to TreeView
            treeTemleNode.ImageList = MyNodeTempleList.imagelist;
            TreeNodeTemple TempTemple = new TreeNodeTemple();

            foreach (String Keys in MyNodeTempleList.ListNode.Keys)
            {
                NodeTemple templedata = MyNodeTempleList.ListNode[Keys];

                TreeNodeTemple treenodetemple = new TreeNodeTemple();
                treenodetemple.Name = templedata.MyName;
                treenodetemple.Text = templedata.MyName;

                treenodetemple.MyDatA = templedata;
                treenodetemple.ToolTipText = templedata.MyName;

                if (templedata.MyLevel == 0)
                {
                    this.treeTemleNode.Nodes.Add(treenodetemple);
                    TempTemple = treenodetemple;
                    treenodetemple.ImageIndex = templedata.IndexImage;
                }
                else
                {
                    TempTemple.Nodes.Add(treenodetemple);
                    treenodetemple.ImageIndex = templedata.IndexImage;
                }
            }
            #endregion
        }
        #endregion

        #region Drag Node Event

        private void treeView1_ItemDrag(object sender, ItemDragEventArgs e)
        {
            TreeView tree = (TreeView)sender;
            TreeNode node = (TreeNode)e.Item;

            if (node != null)
            {
                if (node.Level != 0)
                    tree.DoDragDrop(node.Name, DragDropEffects.Copy);
            }   
        }
        
        private void Temple_ItemDrag(object sender, ItemDragEventArgs e)
        {
            TreeView tree = (TreeView)sender;
            TreeNode node = (TreeNode)e.Item;

            if (node != null)
            {
                //if (node.Level != 0)
                    tree.DoDragDrop(node.Name, DragDropEffects.Copy);
            }
        }

        private void spriteNodeControl1_DragEnter(object sender, DragEventArgs e)
        {
            if (e.Data.GetDataPresent(DataFormats.Text))
                e.Effect = DragDropEffects.Copy;
        }

        private void spriteNodeControl1_DragDrop(object sender, DragEventArgs e)
        {
            //spriteNodeControl1.Massage3 += e.AllowedEffect;
            String SelectNode = (String)e.Data.GetData(DataFormats.Text);
            //TreeNodeEditor node = (TreeNodeEditor)e.Data;
            //spriteNodeControl1.Massage3 = "OK ";
            // spriteNodeControl1.PointToScreen(new System.Drawing.Point((int)spriteNodeControl1.PositioN.X,(int)spriteNodeControl1.PositioN.Y)).ToString() ;

            if (SelectNode != null)
            {
                if(CheckTreeNode(this.treeAdvanceNode,SelectNode))
                {
                    //if (this.treeAdvanceNode.Nodes.ContainsKey(SelectNode))
                    //this.treeAdvanceNode.Nodes[0].Nodes
                    //this.treeView1.Nodes.IndexOfKey(SelectNode);
                    TreeNode[] temp = this.treeAdvanceNode.Nodes.Find(SelectNode, true);
                    TreeNodeEditor Editortemp = (TreeNodeEditor)temp[0];

                    if (Editortemp.Level == 0)
                        e.Effect = DragDropEffects.None;
                    else
                        e.Effect = DragDropEffects.Copy;

                    if (e.Effect == DragDropEffects.Copy)
                    {
                        spriteNodeControl1.NewNode(Editortemp.MyDatA, MousePosition, null);
                    }
                }
                else if (CheckTreeNode(this.treeTemleNode, SelectNode))
                {
                    //if (this.treeTemleNode.Nodes.ContainsKey(SelectNode))
                    TreeNode[] temp = this.treeTemleNode.Nodes.Find(SelectNode, true);
                    TreeNodeTemple Editortemp = (TreeNodeTemple)temp[0];

                        e.Effect = DragDropEffects.Copy;

                    if (e.Effect == DragDropEffects.Copy)
                    {
                        spriteNodeControl1.NewTemple(this.MyNodeList, Editortemp.MyDatA, MousePosition, null);
                        //spriteNodeControl1.NewNode(Editortemp.MyDatA, MousePosition, null);
                    }
                }
            }
        }

        #endregion

        bool CheckTreeNode(TreeView tree,String Key)
        {
            if (tree.Nodes.ContainsKey(Key))
                return true;
            else {
                foreach (TreeNode node in tree.Nodes)
                {

                    if (node.Nodes.ContainsKey(Key))
                        return true;
                }
                return false;
            }
        }

        #region Mouse Control Event

        Vector2 lastClick;
        Vector2 lastPosition;
        private void spriteNodeControl1_MouseDown(object sender, MouseEventArgs e)
        {
            
            if (e.Button == MouseButtons.Middle)
            {
                Cursor = Cursors.SizeAll;
                lastClick = new Vector2(e.X, e.Y);
                lastPosition = this.spriteNodeControl1.camera.MyViewData.Position;
            }
            else if (e.Button == MouseButtons.Left)
            {
                spriteNodeControl1.SelectObject(sender, e);
            }
            
        }
        private void spriteNodeControl1_MouseUp(object sender, MouseEventArgs e)
        {
            spriteNodeControl1.UnSelect(sender, e);
            Cursor = Cursors.Arrow;
        }
        private void spriteNodeControl1_MouseMove(object sender, MouseEventArgs e)
        {
            //
            ///
            this.spriteNodeControl1.UpdateMouseMove(sender, e);

            if (e.Button == MouseButtons.Middle)
            {

                //Cursor = Cursors.SizeAll;
                float tempX = e.X - lastClick.X;
                float tempY = e.Y - lastClick.Y;

                this.spriteNodeControl1.camera.MyViewData.Position = new Vector2(tempX + lastPosition.X, tempY + lastPosition.Y);
            }
            else if (e.Button == MouseButtons.Left)
            {

            }
           // else
                //Cursor = Cursors.Arrow;

            #region Show ToolTip

            NodeObject getnode = spriteNodeControl1.ReturnCollisionNodeObject(e);
            Connecter getconnecter = spriteNodeControl1.ReturnConllisionConnecter(e);
            
            if (getconnecter != null)
            {
                
                //if (toolTip1.ToolTipTitle == "")
                //{

                if (!toolTip1.ShowAlways)
                {
                    toolTip1.ShowAlways = true;
                    toolTip1.ToolTipTitle = getconnecter.MyType.ToString();
                    
                    toolTip1.Show(getconnecter.MySyco.ToString(), spriteNodeControl1, new System.Drawing.Point(e.X, e.Y + 30));
                }
                //}
            }else if (getnode != null)
            {
                //toolTip1.IsBalloon = true;
                //if(toolTip1.ToolTipTitle == "")
                //{
                if (!toolTip1.ShowAlways)
                {
                    toolTip1.ShowAlways = true;
                    NodeBaseControl nodebase = (NodeBaseControl)getnode;
                    toolTip1.ToolTipTitle = getnode.MyData.MyType.ToString();
                    toolTip1.Show(getnode.MyData.Details, spriteNodeControl1, new System.Drawing.Point(e.X, e.Y + 30));
                }
                    //toolTip1.Show(getnode.MyData.Details, spriteNodeControl1, new System.Drawing.Point((int)nodebase.GetShowDetailPosition.X, (int)nodebase.GetShowDetailPosition.Y));
                //}
            }
            else
            {
                toolTip1.ShowAlways = false;
                //toolTip1.UseFading = true;
                //if (toolTip1.ToolTipTitle != "")
                //{
                    //toolTip1.ToolTipTitle = "";
                
                //toolTip1.Hide(spriteNodeControl1);
                //}
            }

            #endregion
        }

        private void spriteNodeControl1_MouseClick(object sender, MouseEventArgs e)
        {
            //spriteNodeControl1.Massage3 = "Click";
            if (e.Button == MouseButtons.Right)
            {
                if (this.spriteNodeControl1.CheckClickNode(sender, e))
                {
                    if (spriteNodeControl1.NodeselecT.MyData.MyType == NodeTypeValue.Draw)
                        NodeProprety.Items[NodeProprety.Items.IndexOfKey("refaceToolStripMenuItem")].Visible = true;
                    else NodeProprety.Items[NodeProprety.Items.IndexOfKey("refaceToolStripMenuItem")].Visible = false ;
                    if (spriteNodeControl1.NodeselecT.MyData.MyType == NodeTypeValue.Screen)
                        NodeProprety.Items[NodeProprety.Items.IndexOfKey("startHereToolStripMenuItem")].Visible = true;
                    else NodeProprety.Items[NodeProprety.Items.IndexOfKey("startHereToolStripMenuItem")].Visible = false;
                    
                    NodeProprety.Show(this.spriteNodeControl1, e.X, e.Y);
                }
                else NodeProprety.Hide();
            }
        }

        private void spritePreviewControl1_MouseDown(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Middle)
            {
                Cursor = Cursors.SizeAll;
                lastClick = new Vector2(e.X, e.Y);
                lastPosition = this.spritePreviewControl1.AimgamecontroL.CamerA.MyViewData.Position;
            }
        }
        private void spritePreviewControl1_MouseMove(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Middle)
            {
                Cursor = Cursors.SizeAll;
                float tempX = e.X - lastClick.X;
                float tempY = e.Y - lastClick.Y;
                this.spritePreviewControl1.AimgamecontroL.CamerA.MyViewData.Position = new Vector2(tempX + lastPosition.X, tempY + lastPosition.Y);
            }
            else Cursor = Cursors.Arrow;
        }

        private void propretyToolStripMenuItem_Click(object sender, EventArgs e)
        {
            this.spriteNodeControl1.NodeselecT.ShowProprety(spriteNodeControl1.backupaction.Temp,spriteNodeControl1.backupaction);
        }

        #endregion

        #region Gen Save and Load Data

        private void spriteNodeControl1_MouseDoubleClick(object sender, MouseEventArgs e)
        {
            if (spriteNodeControl1.ReturnCollisionNodeObject(e) != null)
                spriteNodeControl1.ReturnCollisionNodeObject(e).ShowProprety(spriteNodeControl1.backupaction.Temp,spriteNodeControl1.backupaction);
        }

        private void GenXML_Click(object sender, EventArgs e)
        {
            Cursor = Cursors.WaitCursor;

            SettingEditorData DataSetting = Script.GetSettingFile();
            
            String Scriptpath = System.IO.Path.Combine(DataSetting.MainScriptpath, Script.SubPart);
            // Create a new target folder, if necessary.
            if (!System.IO.Directory.Exists(Scriptpath))
                System.IO.Directory.CreateDirectory(Scriptpath);

            GenerateData(spriteNodeControl1.MainDictionaryType.GetMaindictionarY[NodeTypeValue.Screen.ToString()], System.IO.Path.Combine(Scriptpath, Script.ScreenScriptFile));
            List<int[]> maincout = new List<int[]>();

            #region Create Folder and Data Screen All in Editor

            foreach (String Key in spriteNodeControl1.MainDictionaryType.GetMaindictionarY[NodeTypeValue.Screen.ToString()].Keys)
            {
                NodeScreen screen = (NodeScreen)spriteNodeControl1.MainDictionaryType.GetMaindictionarY[NodeTypeValue.Screen.ToString()][Key];
                String Subscreenpath = System.IO.Path.Combine(Scriptpath, screen.MyData.MyName);
                if (!System.IO.Directory.Exists(Subscreenpath))
                    System.IO.Directory.CreateDirectory(Subscreenpath);

                Dictionary<String, NodeObject> dictionaryMainObjectScreen = new Dictionary<string, NodeObject>();

                Dictionary<String, NodeObject> dictionarytemp = new Dictionary<string, NodeObject>();
                Dictionary<String, NodeObject> dictionarytemp2 = new Dictionary<string, NodeObject>();

                #region Add Update and Draw to temp Dictionary 2
                foreach (String keyUpdate in screen.NodeupdatE.DictionaryObjectUpdate.Keys)
                {
                    dictionaryMainObjectScreen.Add(keyUpdate, screen.NodeupdatE.DictionaryObjectUpdate[keyUpdate]);
                    dictionarytemp2.Add(keyUpdate, screen.NodeupdatE.DictionaryObjectUpdate[keyUpdate]);
                }

                foreach (String keyDraw in screen.NodedrW.DictionaryObjectDraw.Keys)
                {
                    dictionaryMainObjectScreen.Add(keyDraw, screen.NodedrW.DictionaryObjectDraw[keyDraw]);
                    dictionarytemp2.Add(keyDraw, screen.NodedrW.DictionaryObjectDraw[keyDraw]);
                }
                #endregion

                // Camera
                if (spriteNodeControl1.MainDictionaryType.GetMaindictionarY[DictionaryType.MainObejct].ContainsKey(screen.NodeCamerA))
                    dictionaryMainObjectScreen.Add(screen.NodeCamerA, spriteNodeControl1.MainDictionaryType.GetMaindictionarY[DictionaryType.MainObejct][screen.NodeCamerA]);
                // Tack Camera
                foreach(String tackcameraKey in spriteNodeControl1.MainDictionaryType.GetMaindictionarY[NodeTypeValue.TackCamera.ToString()].Keys)
                    screen.NodedrW.DictionaryObjectDraw.Add(tackcameraKey,spriteNodeControl1.MainDictionaryType.GetMaindictionarY[NodeTypeValue.TackCamera.ToString()][tackcameraKey]);
                
                #region Find Object in Target Screen
                int count = 1;
                while (count != 0)
                {

                    count = 0;

                    foreach (String keyStep1 in dictionarytemp2.Keys)
                    {
                        foreach (String subkey in dictionarytemp2[keyStep1].GetPartNode().Keys)
                        {
                            if (!dictionarytemp.ContainsKey(subkey))
                                dictionarytemp.Add(subkey, dictionarytemp2[keyStep1].GetPartNode()[subkey]);
                        }
                        
                    }
                    count = dictionarytemp.Count;
                    dictionarytemp2.Clear();
                    foreach (String keyStep2 in dictionarytemp.Keys)
                    {
                        if(!dictionaryMainObjectScreen.ContainsKey(keyStep2))
                            dictionaryMainObjectScreen.Add(keyStep2, dictionarytemp[keyStep2]);
                        dictionarytemp2.Add(keyStep2, dictionarytemp[keyStep2]);
                    }

                    dictionarytemp.Clear();
                }
                #endregion

                #region Find Sub Update and Sub Draw in Target screen
                foreach (String subkeyupdate in dictionaryMainObjectScreen.Keys)
                    if (dictionaryMainObjectScreen[subkeyupdate].GetType() == typeof(NodeUpdate))
                    {
                        NodeUpdate nodeupdat = (NodeUpdate)dictionaryMainObjectScreen[subkeyupdate];
                        foreach (String keyobjupdate in nodeupdat.DictionaryObjectUpdate.Keys)
                            if (!screen.NodeupdatE.DictionaryObjectUpdate.ContainsKey(keyobjupdate))
                                screen.NodeupdatE.DictionaryObjectUpdate.Add(keyobjupdate, nodeupdat.DictionaryObjectUpdate[keyobjupdate]);
                    }

                foreach (String subkeydraw in dictionaryMainObjectScreen.Keys)
                    if (dictionaryMainObjectScreen[subkeydraw].GetType() == typeof(NodeDraw))
                    {
                        NodeDraw nodedraw = (NodeDraw)dictionaryMainObjectScreen[subkeydraw];
                        foreach(String keyobjdraw in nodedraw.DictionaryObjectDraw.Keys)
                            if (!screen.NodedrW.DictionaryObjectDraw.ContainsKey(keyobjdraw))
                                screen.NodedrW.DictionaryObjectDraw.Add(keyobjdraw, nodedraw.DictionaryObjectDraw[keyobjdraw]);
                    }
                #endregion 

                GenerateData(dictionaryMainObjectScreen, System.IO.Path.Combine(Subscreenpath, Script.MainScriptFile));
                GenerateData(screen.NodedrW.DictionaryObjectDraw, System.IO.Path.Combine(Subscreenpath, Script.DrawScripFile));
                GenerateData(screen.NodeupdatE.DictionaryObjectUpdate, System.IO.Path.Combine(Subscreenpath, Script.UpdateScriptFile));

                foreach (String tackcameraKey in spriteNodeControl1.MainDictionaryType.GetMaindictionarY[NodeTypeValue.TackCamera.ToString()].Keys)
                    screen.NodedrW.DictionaryObjectDraw.Remove(tackcameraKey);

                int[] tempcount = new int[]{dictionaryMainObjectScreen.Count,screen.NodedrW.DictionaryObjectDraw.Count,screen.NodeupdatE.DictionaryObjectUpdate.Count};
                maincout.Add(tempcount);
            }

            #endregion

            // Bug File Use when worng path
            String getfullpath = Path.GetFullPath(Script.SettingFile);
            System.IO.File.Copy(getfullpath, System.IO.Path.Combine(DataSetting.BuildOutput, Script.SettingFile), true);

            CopyFile();
            //GenerateData(spriteNodeControl1.DictionaryObject, System.IO.Path.Combine(DataSetting.MainScriptpath, Script.MainScriptFile));
           

            int[] tempcount2;
            if (maincout.Count > 0)
                tempcount2 = maincout[0];
            else tempcount2 = new int[] { 0, 0, 0 };
            MessageBox.Show("Gen Script Complete "
                + "\n Main objcet : " + tempcount2[0]
                + "\n draw object : " + tempcount2[1]
                + "\n update object : " + tempcount2[2]);

            Cursor = Cursors.Arrow;
        }

        void GenerateData(Dictionary<String, NodeObject> dictionaryObj, String Path)
        {
            ArrayList listdata = new ArrayList();
            foreach (String Key in dictionaryObj.Keys)
                dictionaryObj[Key].SaveData(listdata,SaveMode.Generator);
            
            WriteScriptFile(listdata, Path);
        }

        void CopyFile()
        {
            String contentpath = controlcontentbuilder.contentManager.RootDirectory;

            String Audiospath = System.IO.Path.Combine(contentpath, Script.SubAudio);
            // Create a new target folder, if necessary.
            if (!System.IO.Directory.Exists(Audiospath))
                System.IO.Directory.CreateDirectory(Audiospath);

            foreach (String key in spriteNodeControl1.MainDictionaryType.GetMaindictionarY[NodeTypeValue.IrrklangPlayer.ToString()].Keys)
            {
                NodeIrrKlangPlayer nodeirrklang = (NodeIrrKlangPlayer)spriteNodeControl1.MainDictionaryType.GetMaindictionarY[NodeTypeValue.IrrklangPlayer.ToString()][key];
                String file = nodeirrklang.GetFilE;

                if (File.Exists(nodeirrklang.MyData.Data))
                    System.IO.File.Copy(nodeirrklang.MyData.Data, Path.Combine(Audiospath,nodeirrklang.GetFilE),true);
            }
        }
        /// New gen XML
        /// writh Obj all mainscript in frist
        /// writh list by obj will update or draw

        void SaveDataProject(Dictionary<String, NodeObject> dictionaryObj, String Path)
        {
            ArrayList listdata = new ArrayList();
            Point temp = new Point();

            ArrayList Temp_SaveGroup = new ArrayList();
            spriteNodeControl1.SaveGroup(Temp_SaveGroup);
            spriteNodeControl1.UnminimizeGroup();

            #region Save Data Node
            foreach (String Key in dictionaryObj.Keys)
                dictionaryObj[Key].SaveData(listdata,SaveMode.Project);
            #endregion

            listdata.Add(SaveLoad_PartPosition);

            foreach (String Key in dictionaryObj.Keys)
            {
                NodeObject node = (NodeObject)dictionaryObj[Key];
                foreach (LinkLine linkline in node.LinklineInputForSave)
                {
                    temp.X = (int)linkline.Start.X ;
                    temp.Y = (int)linkline.Start.Y;
                    listdata.Add(temp);

                    temp.X = (int)linkline.End.X;
                    temp.Y = (int)linkline.End.Y;
                    listdata.Add(temp);
                }
            }

            listdata.Add(SaveLoad_PartGroup);

            foreach (object obj in Temp_SaveGroup)
                listdata.Add(obj);

            WriteScriptFile(listdata, Path);

            spriteNodeControl1.MinimizeGroup();
        }

        void WriteScriptFile(ArrayList list, String Path)
        {
            XMLData<Identification> savedata = new XMLData<Identification>();
            Identification identification = new Identification();
            identification.Items = list.ToArray();

            savedata.Save(identification, Path);
        }

        void LoadDataProject(Identification getdata)
        {
            Cursor = Cursors.WaitCursor;

            spriteNodeControl1.ClearALL();
            spriteNodeControl1.camera.MyViewData.Position = Vector2.Zero;

            Point tempPosition;
            bool IsStartGetPosition = false;
            bool IsStartCreateGroup = false;
            if (getdata != null)
            {
                #region New Node
                spriteNodeControl1.CreateLodaData(getdata, MyNodeList);
                #endregion

                #region Get Position to List
                List<Point> MainPositionList = new List<Point>();

                foreach (object obj in getdata.Items)
                {
                    if (obj.GetType() == typeof(Point))
                    {
                        if (IsStartGetPosition)
                        {
                            tempPosition = (Point)obj;
                            MainPositionList.Add(tempPosition);
                        }
                    }
                    else if (obj.GetType() == typeof(String))
                    {
                        String tempSting = (String)obj;
                        if (tempSting == SaveLoad_PartPosition)
                            IsStartGetPosition = true;
                        else if (tempSting == SaveLoad_PartGroup)
                            break;
                    }
                }
                #endregion

                #region Setup Data Afer Load
                spriteNodeControl1.SetupAfterLoadData(getdata);
                #endregion

                #region Update BodyPosition
                System.TimeSpan time = new TimeSpan();
                foreach (String keys in spriteNodeControl1.MainDictionaryType.GetMaindictionarY[DictionaryType.MainObejct].Keys)
                    foreach (Connecter connecter in spriteNodeControl1.MainDictionaryType.GetMaindictionarY[DictionaryType.MainObejct][keys].ListConnectpoint)
                        connecter.UpdateTime(time);
                #endregion 

                #region Connect Position
                List<Point> tempPositionList = new List<Point>();
                foreach (Point position in MainPositionList)
                {
                    tempPositionList.Add(position);
                    if (tempPositionList.Count == 2)
                    {
                        spriteNodeControl1.AutoLinkObject(tempPositionList[0], tempPositionList[1]);
                        tempPositionList.Clear();
                    }
                }
                #endregion

                #region Create Group
                int countIndexItem = 0;
                int count = 0;
                List<NodeObject> listnode = new List<NodeObject>();
                foreach (object obj in getdata.Items)
                {
                    if (obj.GetType() == typeof(StateGroup) && IsStartCreateGroup)
                    {
                        listnode.Clear();
                        StateGroup getstategroup = (StateGroup)getdata.Items.GetValue(countIndexItem);
                        count = (int)getdata.Items.GetValue(countIndexItem + 1);
                        if (count > 0)
                        {
                            String Temp = (String)getdata.Items.GetValue(countIndexItem + 2);
                            for (int i = 0; i < count; i++)
                            {
                                String tempName = Script.GetName(Temp, count, i);
                                if (spriteNodeControl1.MainDictionaryType.GetMaindictionarY[DictionaryType.MainObejct].ContainsKey(tempName))
                                    listnode.Add(spriteNodeControl1.MainDictionaryType.GetMaindictionarY[DictionaryType.MainObejct][tempName]);
                            }
                            spriteNodeControl1.NewGroup(listnode, getstategroup);
                        }
                    }
                    else if (obj.GetType() == typeof(String))
                        if (((String)obj) == SaveLoad_PartGroup)
                            IsStartCreateGroup = true;
                    countIndexItem++;
                }
                #endregion 
            }
            spriteNodeControl1.Start = true;

            MessageBox.Show("Load Project complete");
            
            Cursor = Cursors.Arrow;
        }

        #endregion


   
    }
}
